<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <h1>留言板</h1>
        <div id="box">
            留言标题：<input type="text" id="lytitle" /> 留言内容：
            <textarea id="lycon" name="" id="" cols="30" rows="10"></textarea>
            留言人：<input id="lyp" type="text" />
            <button id="sendLy">发布留言</button>
        </div>
        <hr />

        <div id="lylist"></div>
    </body>
    <script src="../11.9作业/ajax.js"></script>
    <script>
        window.onload = function () {
            getList()
            document.getElementById('sendLy').addEventListener('click', sendFun)
            lylist.addEventListener('click', function (e) {
                if (e.target.nodeName == 'A') {
                    event.preventDefault()
                    delLy(e.target.title)
                }
            })
        }
        function delLy(id) {
            ajax({
                url: 'https://liu.zzgoodqc.cn/lyb/del?id=' + id,
                success: function (res) {
                    getList()
                },
            })
        }
        function sendFun() {
            ajax({
                url: 'https://liu.zzgoodqc.cn/lyb/add',
                type: 'post',
                data: {
                    title: lytitle.value,
                    content: lycon.value,
                    name: lyp.value,
                },
                success: function (res) {
                    if (res.code == 200) {
                        getList()
                    }
                },
            })
        }
        function getList() {
            ajax({
                url: 'https://liu.zzgoodqc.cn/lyb/list',
                success: function (res) {
                    console.log(res)
                    render(res.data)
                },
            })
        }
        function render(data) {
            data.sort((a, b) => b.id - a.id)
            let html = ''
            data.forEach((item, index) => {
                html += `<div>
                            <h3>标题: <span>${item.title}</span></h3>
                            <p>内容：<span>${item.content}</span></p>
                            <p>留言人: <span>${item.name}</span></p>
                            <p>留言时间： <span>${item.created_at}</span><a href="#" title='${item.id}'>删除</a></p>
                        </div><hr />`
            })
            lylist.innerHTML = html
        }
    </script>
</html>
